import { defineStore } from 'pinia'
import router from '@/router'
import {
  accountLoginRequest,
  requestUserInfoById,
  requestUserMenusByRoleId
} from '@/service/login/login'
import type { IAccount, IUserInfoResult, IUserMenu } from '@/service/login/type'
import { localCache, mapMenusToRoutes } from '@/utils'

interface ILoginState {
  token: string
  userInfo: IUserInfoResult | null
  userMenus: IUserMenu[]
}

interface Phone {
  num: string
  code: string
}

const useLoginStore = defineStore('login', {
  state: (): ILoginState => ({
    token: '',
    userInfo: null,
    userMenus: []
  }),
  actions: {
    changeToken(token: string) {
      this.token = token
    },
    changeUserInfo(userInfo: IUserInfoResult) {
      this.userInfo = userInfo
    },
    changeUserMenus(userMenus: IUserMenu[]) {
      this.userMenus = userMenus
      // userMenus => routes
      const routes = mapMenusToRoutes(this.userMenus)

      // 将 routes => router.main.children
      routes.forEach((route) => {
        router.addRoute('main', route)
      })
    },
    async accountLoginAction(account: IAccount) {
      // 1. 实现登录逻辑
      const loginResult = await accountLoginRequest(account)
      const { id, token } = loginResult.data
      this.changeToken(token)
      localCache.setCache('token', token)

      // 2. 请求用户信息
      const userInfoResult = await requestUserInfoById(id)
      const userInfo = userInfoResult.data
      this.changeUserInfo(userInfo)
      localCache.setCache('userInfo', userInfo)

      // 3. 请求用户菜单
      const userMenusResult = await requestUserMenusByRoleId(userInfo.role.id)
      const userMenus = userMenusResult.data
      this.changeUserMenus(userMenus)
      localCache.setCache('userMenus', userMenus)

      // 4. 跳转到首页
      router.push('/main')
    },
    loadLocalLogin() {
      const token = localCache.getCache('token')
      if (token) {
        this.changeToken(token)
      }
      const userInfo = localCache.getCache('userInfo')
      if (userInfo) {
        this.changeUserInfo(userInfo)
      }
      const userMenus = localCache.getCache('userMenus')
      if (userMenus) {
        this.changeUserMenus(userMenus)
      }
    },
    phoneLoginAction({ num, code }: Phone) {
      console.log('执行phoneLoginAction', num, code)
    }
  }
})

export default useLoginStore
